package com.server.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author driver-design
 * @description BIO
 * @date 2022/4/10
 */
public class BIOServer {

    public static void main(String[] args) throws Exception {
        ExecutorService threadPoolExecutor =  new ThreadPoolExecutor(
                10,
                20,
                1,
                TimeUnit.MINUTES,
                new LinkedBlockingDeque<>(10000),
                new ThreadFactory() {
                    public Thread newThread(Runnable runnable) {
                        return new Thread(runnable, "schema_test_threadPool_" + runnable.hashCode());
                    }
                }
        );

        // 创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(8888);

        System.out.println("服务器启动了...");

        while (true){
            // 监听客户端连接
            Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端: client port :"+ socket.getPort());

            // 线程池
            threadPoolExecutor.execute(() -> {
                // 客户端通信方法
                handler(socket);
            });
        }
    }

    // 与客户端通信的具体方法
    public static void handler(Socket socket){
        byte[] bytes = new byte[1024];
        // 通过 socket获取InputStream
        try {
            // 获取线程信息
            System.out.println("线程信息, id = " + Thread.currentThread().getId() + ", name = " + Thread.currentThread().getName());

            InputStream inputStream = socket.getInputStream();

            // 循环读取客户端发送的消息
            while (true) {
                int read = inputStream.read(bytes);
                if (read != -1) {
                    // 输出客户端发送的数据
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭与client的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
